package com.example.elm.CartAndOrder

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.elm.R
import com.example.elm.databinding.CartMainBinding
import android.content.Intent
import android.util.Log
import android.widget.Button
import android.widget.CheckBox
import android.widget.Toast
import com.example.elm.Public.CartGoodsInfo
import com.example.elm.Public.MyApplication
import okhttp3.OkHttpClient
import okhttp3.Request
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.io.BufferedReader
import java.io.DataOutputStream
import java.io.InputStreamReader
import java.io.StringReader
import java.net.HttpURLConnection
import java.net.URL
import kotlin.concurrent.thread

class CartMainFragment:Fragment() {
    private var productList = ArrayList<CartGoodsInfo>()
    private var selectedList = ArrayList<Boolean>()
    private val server_ip = MyApplication.serverIp
    private var maxId = MyApplication.maxId
    private var cost = 0.0
    private lateinit var binding: CartMainBinding
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // 返回 cart_main.xml 对应的绑定视图
        binding = CartMainBinding.inflate(inflater, container, false)
        // 初始化数据
        ReadCartGoodsByXml()
        return binding.root

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 设置 RecyclerView
        val layoutManager = LinearLayoutManager(requireContext())
        binding.cartRecycler.layoutManager = layoutManager
        val adapter = ProductAdapter(productList,selectedList,cost,requireContext())
        binding.cartRecycler.adapter = adapter

        binding.cost.text = "${cost}"

        val checkAll = binding.CheckAll
        // 点击全选按钮
        checkAll.setOnCheckedChangeListener { _, isChecked ->
            adapter.setAllChecked(isChecked) // 设置所有 CheckBox 的选中状态
        }

        binding.DelAll.setOnClickListener {
            showDelAllPickerDialog()
            adapter.notifyDataSetChanged()
        }

        //点击一键结算
        binding.confirmButton.setOnClickListener {
            // 筛选选中的商品
            val selectedProducts = ArrayList<CartGoodsInfo>()
            for (i in productList.indices) {
                if (selectedList[i]) {
                    selectedProducts.add(productList[i])
                }
            }
            // 将选中的商品列表通过 Intent 传递
            val intent = Intent(requireContext(), ConfirmOrderActivity::class.java)
            intent.putExtra("selected_products", selectedProducts) // 传递商品列表
            startActivity(intent)
        }
    }


    private fun showDelAllPickerDialog() {
        val options = arrayOf("确定清除", "取消清除")
        val builder = android.app.AlertDialog.Builder(context)
        builder.setTitle("您确定要清除购物车吗？")
        builder.setItems(options) { _, which ->
            when (which) {
                0 -> { // 用户选择“确定删除”
                    Del_all_CartGoods() // 调用删除操作
                }
                1 -> { // 用户选择“取消删除”
                    // 不做任何操作，对话框会自动关闭
                }
            }
        }
        builder.show()
    }

    // 将每行layout文件，代码与控件关联
    private class ViewHolder(view:View): RecyclerView.ViewHolder(view) {
        val image = view.findViewById<ImageView>(R.id.shoptu)
        val store = view.findViewById<TextView>(R.id.cantingName)
        val price = view.findViewById<TextView>(R.id.tvPrice)
        val name = view.findViewById<TextView>(R.id.tvFoodName)
        val info = view.findViewById<TextView>(R.id.tvSpiciness)
        val count = view.findViewById<TextView>(R.id.tvCount)
        val checkItem = view.findViewById<CheckBox>(R.id.checkItem)
        val cartGoodsDle = view.findViewById<Button>(R.id.CartGoodDel)
    }
    // 适配器，填充数据
    private class ProductAdapter(val productList:ArrayList<CartGoodsInfo>,
                                 val selectedList:ArrayList<Boolean>,
                                 var cost:Double,
                                 private val context: Context
                                 //private val costChangedListener: OnCostChangedListener
    ): RecyclerView.Adapter<ViewHolder> () {
        private val server_ip = MyApplication.serverIp
        init {
            for (i in productList.indices) {
                selectedList.add(false) // 默认所有商品的选中状态为 false
            }
        }
        // 设置所有 CheckBox 的状态
        fun setAllChecked(isChecked: Boolean) {
            for (i in selectedList.indices) {
                selectedList[i] = isChecked // 更新所有选中状态
            }
            notifyDataSetChanged() // 刷新 RecyclerView
        }
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.cart_item,parent,false)


            return ViewHolder(view)
        }
        //
        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val info = productList[position]
            val imageResId = holder.itemView.context.resources.getIdentifier(
                info.image, "drawable", holder.itemView.context.packageName
            )
            if (imageResId != 0) {
                holder.image.setImageResource(imageResId)
            } else {
                holder.image.setImageResource(R.drawable.cqxm)
            }    // 设置图标
            holder.store.text = info.store               // 餐厅名称
            holder.name.text = info.name                 // 菜品名称
            holder.info.text = "辣度：${info.info}"  // 辣度
            holder.count.text = "份数 x${info.count}"          // 份数
            holder.price.text = "¥${info.price}"          // 价格
            // 设置小 CheckBox 的选中状态
            holder.checkItem.isChecked = selectedList[position]
            // 设置 CheckBox 的监听器
            holder.checkItem.setOnCheckedChangeListener { _, isChecked ->
                selectedList[position] = isChecked // 更新选中状态
                if (isChecked) {
                    cost += productList[position].price
                } else {
                    cost -= productList[position].price
                }
                // 使用接口回调更新主界面
                //costChangedListener.onCostChanged(cost)
            }
            //删除购物车单个项目
            holder.cartGoodsDle.setOnClickListener {
                showDelPickerDialog(info.id)
                notifyDataSetChanged() // 刷新界面
            }

        }
        private fun showDelPickerDialog(itemId: Int) {
            val options = arrayOf("确定删除", "取消删除")
            val builder = android.app.AlertDialog.Builder(context)
            builder.setTitle("您确定要删除该商品吗？")
            builder.setItems(options) { _, which ->
                when (which) {
                    0 -> { // 用户选择“确定删除”
                        delGoodByIdPost(itemId) // 调用删除操作
                    }
                    1 -> { // 用户选择“取消删除”
                        // 不做任何操作，对话框会自动关闭
                    }
                }
            }
            builder.show()
        }

        override fun getItemCount(): Int {
            return productList.size
        }
        // 通过id删除
        fun delGoodByIdPost(id:Int){
            val del_goods_jsp = "http://$server_ip:8080/CartAndOrder/del_CartGoods.jsp"
            thread {
                var connection : HttpURLConnection? = null
                try {
                    val response = StringBuilder()
                    val url = URL(del_goods_jsp)
                    connection = url.openConnection() as HttpURLConnection
                    connection.connectTimeout = 8000 //  连接 超时
                    connection.readTimeout = 8000 // read 超时时间
                    connection.requestMethod = "POST"
                    val output = DataOutputStream(connection.outputStream)
                    output.writeBytes("id=$id")
                    val input = connection.inputStream
                    //  读取输入流，类似与文件流
                    val reader = BufferedReader(InputStreamReader(input))
                    reader.use{
                        reader.forEachLine {
                            response.append(it)
                        }
                    }
                    // 根据id找到索引
                    val index = productList.indexOfFirst { it.id == id }
                    if (index != -1) { // 确保找到了对应的项
                        productList.removeAt(index) // 移除该项
                        selectedList.removeAt(index) // 同时移除选中状态
                    }
                    showResponse(response.toString())
                }
                catch (e: Exception){
                    e.printStackTrace()
                }
                finally {
                    connection?.disconnect()
                }
            }
        }
        fun showResponse(response:String){
            Log.d("删除成功",response)
        }
    }
    fun Del_all_CartGoods() {
        val del_all_goods_jsp = "http://$server_ip:8080/CartAndOrder/del_all_CartGoods.jsp"
        thread {
            var connection : HttpURLConnection? = null
            try {
                val response = StringBuilder()
                val url = URL(del_all_goods_jsp)
                connection = url.openConnection() as HttpURLConnection
                connection.connectTimeout = 8000 //  连接 超时
                connection.readTimeout = 8000 // read 超时时间
                connection.requestMethod = "POST"
                val output = DataOutputStream(connection.outputStream)
                output.writeBytes("")
                val input = connection.inputStream
                //  读取输入流，类似与文件流
                val reader = BufferedReader(InputStreamReader(input))
                reader.use{
                    reader.forEachLine {
                        response.append(it)
                    }
                }
                productList.clear()
                selectedList.clear()

                showResponse(response.toString())
            }
            catch (e: Exception){
                e.printStackTrace()
            }
            finally {
                connection?.disconnect()
            }
        }
    }
    fun showResponse(response:String){
        Log.d("全部数据删除成功",response)
    }
    // 通过xml读取
    fun ReadCartGoodsByXml(){
        val cartGoods_all = "http://$server_ip:8080/CartAndOrder/get_all_CartGoods_xml.jsp"
        thread {
            try{
                val client = OkHttpClient()
                val request: Request = Request.Builder()
                    .url(cartGoods_all)
                    .build()
                val response = client.newCall(request).execute()
                val responseData = response.body?.string()
                // 确保在主线程更新 UI
                requireActivity().runOnUiThread {
                    if (!responseData.isNullOrEmpty()) {
                        parseXml(responseData.trim()) // 解析返回的数据
                    } else {
                        Log.d("CartGetGoods", "没有数据")
                    }
                }

            }
            catch (e: Exception){
                e.printStackTrace()
                Log.d("CartGetGoods", "加载失败，请检查网络")
            }
        }
    }
    // 解析xml
    fun parseXml(xmlStr: String): String{
        try {
            val factory = XmlPullParserFactory.newInstance()
            val xmlPullPaser = factory.newPullParser()
            // 设置xml解析器的输入
            xmlPullPaser.setInput(StringReader(xmlStr))
            productList.clear()
            var eventType = xmlPullPaser.eventType//  事件类型
            var idStr = ""
            var image = ""
            var store = ""
            var priceStr = ""
            var name = ""
            var info = ""
            var countStr = ""
            while(eventType != XmlPullParser.END_DOCUMENT){
                val nodeName = xmlPullPaser.name
                // builder.append("${nodeName}--")
                when(eventType) {
                    // 标签开始
                    XmlPullParser.START_TAG -> {
                        when (nodeName) {
                            "image" -> image = xmlPullPaser.nextText()
                            "store" -> store = xmlPullPaser.nextText()
                            "price" -> priceStr = xmlPullPaser.nextText()
                            "name" -> name = xmlPullPaser.nextText()
                            "info" -> info = xmlPullPaser.nextText()
                            "count" -> countStr = xmlPullPaser.nextText()
                            "id" -> idStr = xmlPullPaser.nextText()
                        }
                    }
                    // 标签结束
                    XmlPullParser.END_TAG -> {
                        if ("Good" == nodeName) {
                            productList.add(
                                CartGoodsInfo(
                                    image,
                                    store,
                                    priceStr.toDoubleOrNull()?:0.0,
                                    name,
                                    info,
                                    countStr.toIntOrNull()?:1,
                                    idStr.toIntOrNull()?:0
                                )
                            )
                            selectedList.add(false)
                            val tempId = idStr.toIntOrNull()?:0
                            if (tempId >= maxId) {
                                maxId = tempId
                                MyApplication.maxId = maxId
                            }
                        }
                    }
                }
                eventType = xmlPullPaser.next() //  读取下一个，进行遍历
            }
            Log.d("MAXIDSTR","${idStr}")
            Log.d("MAXID","${maxId}")
            if (isAdded) {
                binding.cartRecycler.adapter?.notifyDataSetChanged()
            }
        }
        catch (e: Exception){
            e.printStackTrace()
        }
        return ""
    }
}